package cn.xspace.wnx.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.xspace.android.xafcommon.base.BaseFragment;
import com.xspace.android.xafcommon.base.PagerInfoView;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.ErrorCode;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.HypyUtil;
import com.xspace.android.xafcommon.util.JSONUtil;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.ResourceUtils;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.chatui.bean.MsgRecordEntity;
import cn.xspace.library.bean.Type;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import cn.xspace.wnx.activity.ChatInfoActivity;
import cn.xspace.wnx.activity.MsgForwardActivity;
import cn.xspace.wnx.adapter.MyGroupsAdapter;
import cn.xspace.wnx.entity.GroupEntity;
import cn.xspace.wnx.entity.MyGroupBean;
import cn.xspace.wnx.util.ForwardHelper;
import cn.xspace.wnx.util.Navigator;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Wubj 创建于 2016/12/27 0027.
 */
public class MyGroupsFragment extends BaseFragment {

    public static final String TAG = MyGroupsFragment.class.getSimpleName();

    private ListView mListView;
    private PagerInfoView mPagerInfo;
    private TextView tvTitle, tvInfo;
    private ImageView ivInfo;
//    private Button btReload;
//    private RelativeLayout rlGroupsInfo;
    private LinearLayout llTitle;
    private MsgRecordEntity recordEntity; //转发时用到的
    private HashMap<Integer, List<GroupEntity>> dataMap;
    private String user_id;
    private MyGroupsAdapter mGroupsAdapter;

    private List<GroupEntity> proGroups = new ArrayList<>();
    private List<GroupEntity> comGroups = new ArrayList<>();
    private String[] groupsType = ResourceUtils.getStringArray(R.array.group_type);

    //拼音首字母排序
    private Comparator comparator = new Comparator<GroupEntity>() {
        @Override
        public int compare(GroupEntity lhs, GroupEntity rhs) {
            if (TextUtils.isEmpty(lhs.shotKey)) {
                return -1;
            }
            String key1 = lhs.shotKey.toUpperCase();
            Integer num1 = HypyUtil.chartSortMap.get(key1);
            String key2 = rhs.shotKey.toUpperCase();
            Integer num2 = HypyUtil.chartSortMap.get(key2);
            if (num1 == null) {
                return -1;
            }
            if (num2 == null) {
                return 1;
            }
            return num1.compareTo(num2);
        }
    };

    public MyGroupsFragment() {
        EventBus.getDefault().register(this);
    }

    @Override
    protected void getIntentData() {
        super.getIntentData();
        if (fragmentArgs != null) { //转发时用到的参数
            recordEntity = (MsgRecordEntity) fragmentArgs.getSerializable(MsgForwardActivity.FORWARD_ENTITY);
        }
    }

    @Override
    public View initView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_my_groups, null);
    }

    @Override
    protected void initFindViewById(View view) {
        mListView = (ListView) view.findViewById(R.id.lv_my_groups);
        mPagerInfo = (PagerInfoView) view.findViewById(R.id.layout_group_info);

        llTitle = (LinearLayout) view.findViewById(R.id.ll_group_title);
        tvTitle = (TextView) view.findViewById(R.id.tv_group_title);
        tvInfo = (TextView) view.findViewById(R.id.tv_net_work_info);
        ivInfo = (ImageView) view.findViewById(R.id.iv_net_work_info);

//        btReload = (Button) view.findViewById(R.id.bt_net_work_reload);
//        rlGroupsInfo = (RelativeLayout) view.findViewById(R.id.layout_group_info);
//        btReload.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                initData();
//            }
//        });
    }

    @Override
    protected void initEvent() {
        mPagerInfo.setOnReloadClickListener(new PagerInfoView.OnReloadClickListener() {
            @Override
            public void onReloadClick(View v) {
                initData();
            }
        });
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            // 滚动状态变化,静止-->滚动,滚动-->静止
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            // 在滚动时调用的程序
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (proGroups != null && comGroups != null) {
                    if (firstVisibleItem > proGroups.size()) {
                        tvTitle.setText(groupsType[2]);
                    } else {
                        tvTitle.setText(groupsType[1]);
                    }
                }
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0 || position == proGroups.size() + 1) {
                    return;
                } else {
                    final GroupEntity group;
                    if (position <= proGroups.size()) {
                        group = proGroups.get(position - 1);
                    } else {
                        group = comGroups.get(position - 1 - proGroups.size() - 1);
                    }
                    if (recordEntity != null) {
                        ForwardHelper.getInstance().confirmBeforeForward(mContext, new ButtonClickListener() {
                            @Override
                            public void buttonClick(View view) {
                                ForwardHelper.getInstance().sendMessageGroup(mContext, recordEntity, group);
                                Map<String, Object> event = new HashMap<String, Object>();
                                event.put(EventBusConstant.TYPE, EventBusConstant.FINISH_PAGE_FORWARD);
                                EventBus.getDefault().post(event);
                                getActivity().finish();

                            }
                        }, recordEntity, group.group_name);
                    } else {
                        Bundle dataBundle = new Bundle();
                        dataBundle.putString(BldNavigation.SENDER_ID, group.group_id);
                        dataBundle.putInt(BldNavigation.CHAT_TYPE, MsgType.CHAT_CROUP.toNumber());
                        dataBundle.putString(BldNavigation.CHAT_NAME, group.group_name);
                        dataBundle.putString(BldNavigation.CHAT_SENDER_LOGO, group.group_logo);
                        dataBundle.putInt(BldNavigation.GROUP_TYPE, group.group_type);
                        dataBundle.putSerializable(MsgForwardActivity.FORWARD_ENTITY, recordEntity);
                        Navigator.startChatActivity(mContext, dataBundle);
                    }
                }
            }
        });
    }

    @Override
    public void initData() {
        try {
//            rlGroupsInfo.setVisibility(View.GONE);
            dataMap = new HashMap<>();
            user_id = MyInfoUtil.getMyUserid(mContext);
            requestNetWork();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 访问网络获取数据
     */
    private void requestNetWork() {
        showWaitDialog();
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("user_id", user_id);
        OkHttpManager.getInstance().commonRequest(Constants.QUERY_USER_ALL_GROUP, paramsMap)
                .map(new Func1<BaseReturnBean, MyGroupBean>() {
                    @Override
                    public MyGroupBean call(BaseReturnBean baseReturnBean) {
                        if (!ErrorCode.SUCCESS_CODE_WNX.equals(baseReturnBean.code)) {
                            T.showShort(mContext, R.string.network_error);
                            return null;
                        }
                        MyGroupBean myGroupBean = JSONUtil.parseJsonToBean(baseReturnBean.data, MyGroupBean.class);
                        LogUtil.d(TAG, "wubaojie>>>call: " + myGroupBean.toString());
                        return myGroupBean;
                    }
                })
                .doOnNext(new Action1<MyGroupBean>() {
                    @Override
                    public void call(MyGroupBean myGroupBean) {
//                        proGroups = myGroupBean.progroupList; // TODO 专业群组隐藏
                        comGroups = myGroupBean.cgroupList;
                        for (GroupEntity proGroup : proGroups) {
                            proGroup.shotKey = HypyUtil.cn2py(proGroup.group_name);
                        }
                        for (GroupEntity comGroup : comGroups) {
                            comGroup.shotKey = HypyUtil.cn2py(comGroup.group_name);
                        }
                        Collections.sort(proGroups, comparator);
                        Collections.sort(comGroups, comparator);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<MyGroupBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        mPagerInfo.showNetWorkError();
//                        setOnErrorView();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(MyGroupBean myGroupBean) {
                        dataMap.clear();
                        dataMap.put(Type.GroupType.NORMAL, comGroups);
                        dataMap.put(Type.GroupType.PROFESSIONAL, proGroups);
                        hideWaitDialog();

                        refresh();
                    }
                });
    }

    /**
     * 无网络时显示的内容
     */
//    private void setOnErrorView() {
//        tvInfo.setText(R.string.net_work_error);
//        ivInfo.setImageResource(R.drawable.net_work_error);
//        rlGroupsInfo.setVisibility(View.VISIBLE);
//    }

    /**
     * 刷新列表的方法
     */
    private void refresh() {
        if (mGroupsAdapter == null) {
            mGroupsAdapter = new MyGroupsAdapter(mContext, dataMap);
            mListView.setAdapter(mGroupsAdapter);
        } else {
            mGroupsAdapter.notifyDataSetChanged();
        }
//        llTitle.setVisibility(View.VISIBLE); //不显示
        tvTitle.setText(groupsType[1]);
       if (proGroups.size() == 0 && comGroups.size() == 0) {
           mPagerInfo.showPageEmpty(R.string.groups_empty);
//            tvInfo.setText(R.string.groups_empty);
//            ivInfo.setImageResource(R.drawable.icon_common_empty);
//            btReload.setVisibility(View.GONE);
//            rlGroupsInfo.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onEventMainThread(Map<String, Object> inParam) {
        LogUtil.d(inParam.toString());
        super.onEventMainThread(inParam);
        if (TAG.equals(inParam.get(EventBusConstant.TYPE))) {
            if (ChatInfoActivity.GROUP_DELETE.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                String groupId = (String) inParam.get(EventBusConstant.ACTION_VALUE);
                LogUtil.d(TAG, "wubaojie>>>delete group groupId: " + groupId);
                for (GroupEntity entity : comGroups) {
                    if (entity.group_id.equals(groupId)) {
                        comGroups.remove(entity);
                        mGroupsAdapter.notifyDataSetChanged();
                        break;
                    }
                }
            } else if (ChatInfoActivity.GROUP_NAME_CHANGE.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                GroupEntity groupEntity = (GroupEntity) inParam.get(EventBusConstant.ACTION_VALUE);
                if (groupEntity == null)
                    return;
                LogUtil.d("change group name :" + groupEntity.toString());
                for (GroupEntity entity : comGroups) {
                    if (entity.group_id.equals(groupEntity.group_id)) {
                        entity.group_name = groupEntity.group_name;
                        mGroupsAdapter.notifyDataSetChanged();
                        break;
                    }
                }
            }
        }
    }
}
